/**
作者：chencheng73@163.com
时间：2018-01-26
描述：
1.后台POST/GET请求交互
2.表单、字符串处理工具类
**/

var requestTimeOut = 5000// 后台请求超时设置

var utilModule = (function() {

	return {

		/**
		 * post方法
		 * @param confObj
		 * @returns {boolean}
		 */
		post: function(confObj) {
			if(typeof confObj == "undefined") {
				confObj = {};
			}
			var defConf = {
				supportCors: true,
				commonUrl: null,
				needJson: true,
				url: "",
				data: {},
				timeout: requestTimeOut,
				async: true,
				crossDomain: true,
				headers: {
					Accept: "application/json; charset=utf-8"
				},
				contentType: "application/json",
				beforeSend:function(){
					utilModule.showLoading("html-loding");
				},
				success: function(data) {

				},
				error: function(xml, XMLHttpRequest, errMsg, e) {
					return false;
				},
				complete: function () {
    			  utilModule.closeLoading("html-loding");
				}
			};
			var setting = $.extend(true, defConf, confObj);
			if(!setting.url) {
				//utilModule.showMsgTitle("请先配置请求路径");
				return false;
			}
			$.ajax({
			     url: (setting.commonUrl ? setting.commonUrl : serverUrl)+ setting.url,
				data: setting.needJson ? JSON.stringify(setting.data) : setting.data,
				type: "post",
				dataType: "JSON",
				async: setting.async,
				timeout: setting.timeout,
				headers: setting.headers,
				beforeSend:setting.beforeSend,
				success: function(response) {
					var _returnInfo = null;
					if(typeof(response)=="object"){
					   	_returnInfo=response;
					}else{
						_returnInfo=eval("(" + response + ")");
					}
					if(_returnInfo.status ==500){
						alert(_returnInfo)
					    mui.alert("服务器异常!");
						return false;
					}
					
					//状态码200,自动返回result，否则自行处理
					var returnResult=utilModule.checkUndefined(_returnInfo.result);
					if(_returnInfo.status ==200 &&returnResult!=""){
						setting.success(_returnInfo.result);
				   }else{
						setting.success(_returnInfo);
				   }
					
				},
				error: function(responseText) {
					setting.error(responseText);
				},
				complete:setting.complete
			});
		},

		/**
		 * get请求方法。参数类型{url：‘’，data：‘’}
		 * @param confObj
		 * @returns {boolean}
		 */
		get: function(confObj) {
			if(typeof confObj == "undefined") {
				confObj = {};
			}
			if(typeof confObj.commonUrl == 'undefined') {

			}
			var defConf = {
				supportCors: true,
				commonUrl: null,
				url: "",
				data: {},
				timeout: requestTimeOut,
				async: true,
				crossDomain: true,
				cache: false,
				headers: {
					Accept: "application/json; charset=utf-8"
				},
				success: function() {},
				error: function(xml, XMLHttpRequest, errMsg, e) {}
			};
			var setting = $.extend(true, defConf, confObj);
			if(!setting.url) {
				return false;
			}
			$.ajax({
			     url: (setting.commonUrl ? setting.commonUrl : serverUrl) + setting.url,
				data: setting.data,
				type: "get",
				dataType: "JSON",
				async: setting.async,
				timeout: setting.timeout,
				headers: setting.headers,
				success: function(response) {
					var _returnInfo = null;
					if(typeof(response)=="object"){
					   	_returnInfo=response;
					}else{
						_returnInfo=eval("(" + response + ")");
					}
					
					if(_returnInfo.status ==500){
					    mui.alert("服务器异常!");
						return false;
					}
					//状态码200,自动返回result，否则自行处理
					var returnResult=utilModule.checkUndefined(_returnInfo.result);
					if(_returnInfo.status ==200 &&returnResult!=""){
						setting.success(_returnInfo.result);
				   }else{
						setting.success(_returnInfo);
				   }
				},
				error: function(response) {
					setting.error(response);
				}
			});
		},

		/**
		 * get请求
		 * @param param
		 * @param callback
		 */
		getRequest: function getRequest(url, async, param, callback, column) {
			if(!param) {
				param = {};
			}
			utilModule.get({
				url: url,
				data: param,
				async: async,
				success: function(response) {
					console.log(url + "getRequest路径获取结果为", response);

					if(column ? response[column] > 0 : response.result == 200) {
						if(typeof callback == "function") {
							callback(response.data);
						}
					} else if(response.status == 200) {
						if(typeof callback == "function") {
							callback(response.responseText);
						}
					} else {
						utilModule.showMsgTitle(response.msg);
					}
				},
				error: function(response) {
					setting.error(response);
				}
			});
		},
		/**
		 * post请求
		 * @param param
		 * @param callback
		 */
		postRequest: function getRequest(url, async, param, callback, column) {
			if(!param) {
				param = {};
			}
			utilModule.post({
				url: url,
				data: param,
				async: async,
				success: function(response) {
					console.log(url + "路径获取结果为", response);

					if(column ? response[column] > 0 : response.result == 200) {
						if(typeof callback == "function") {
							callback(response.data);
						}
					}
				},
				error: function(response) {

				}
			});
		},

		/**
		 * 将list转换为map
		 * @param key map中作为key的列名
		 * @param value map中作为value的列名
		 * @param list 循环的list
		 */
		parseListToMap: function(key, value, list) {
			var map = {};
			if(list && list.length) {
				for(var i = 0; i < list.length; i++) {
					var data = list[i];
					if(data[key]) {
						map[data[key]] = data[value];
					}
				}
			}
			return map;
		},

		/**
		 * 设置localStorage
		 * @param key key
		 * @param value value
		 */
		setStorage: function(key, value) {
			localStorage.setItem(key, value);
		},

		/**
		 * 获取Storage
		 * @param key
		 * @returns {string}
		 */
		getStorage: function(key) {
			return localStorage.getItem(key);
		},

		/**
		 * 删除Storage
		 * @param key
		 */
		removeStorage: function(key) {
			localStorage.removeItem(key);
		},
		/**
		 * 清空LocalStorage
		 */
		clearStorage: function() {
			localStorage.clear();
		},

		/**
		 * 渲染数据并显示
		 * @param contStr domid
		 * @param renderId scriptid
		 * @param data
		 */
		renderHtml: function(contStr, renderId, data) {
			if(typeof data == "undefined") {
				data = {};
			}
			var html = template(renderId, data);
			$(contStr).html(html);
		},
		appendHtml: function(contStr, renderId, data) {
			if(typeof data == "undefined") {
				data = {};
			}
			var html = template(renderId, data);
			$(contStr).append(html);
		},
		
		/**
		 * 清空Form数据
		 * @param {Object} $formObj
		 */
		clearFormData: function($formObj) {
			$formObj.validate().resetForm();
			$formObj.find(".form-control").val(""); //清空输入框
			$formObj.find("select.form-control > option:first").prop("selected", true); //清除下拉框选中的selected属性
			$formObj.find("input.text-danger").removeClass("text-danger");
		},
		
		/**
		 * 统计字符长度
		 * @param sSource
		 * @returns {number}
		 */
		countStringLength: function(sSource) {
			var len = 0;
			var charCodeNo;
			for(var i = 0; i < sSource.length; i++) {
				charCodeNo = sSource.charCodeAt(i);
				var charLen = charCodeNo > 0 && charCodeNo < 128 ? 1 : 2;
				len += charLen;
			}
			return len;
		},

		/**
		 * 数字字符串补零
		 * @param num
		 * @returns {*}
		 */
		zeroFill: function(num) {
			if(num > 0 && num < 10 || num.toString().length == 1 && num == 0) {
				return '0' + num;
			}
			return num;
		},
		/**
		 * 获取浏览器地址栏中参数
		 * @param name
		 * @returns {null}
		 */
		getQueryString: function(name) {
			var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
			var r = window.location.search.substr(1).match(reg);
			if(r != null) return unescape(r[2]);
			return null;
		},
		/**
		 * encodeURIComponent
		 * @param {Object} name
		 */
		encodeURIComponent: function(name) {
			return encodeURIComponent(name);
		},
		/**
		 * decodeURIComponent
		 * @param {Object} name
		 */
		decodeURIComponent: function(name) {
			var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
			var r = window.location.search.substr(1).match(reg);
			if(r != null) return decodeURIComponent(r[2]);
			return null;
		},
		/**
		 * 返回浏览页面
		 */
		historyBack: function() {
			window.history.go(-1);
		},
		/**
		 * 判断设备是手机还是pc
		 * @returns {boolean}
		 * @constructor
		 */
		isPC: function() {
			var userAgentInfo = navigator.userAgent;
			var Agents = ["Android", "iPhone",
				"SymbianOS", "Windows Phone",
				"iPad", "iPod"
			];
			var flag = true;
			for(var v = 0; v < Agents.length; v++) {
				if(userAgentInfo.indexOf(Agents[v]) > 0) {
					flag = false;
					break;
				}
			}
			return flag;
		},
		/**
		 * geturl 获取参数
		 * @returns {Object}
		 */
		qtLocationUrl: function() {
			var url = location.search;
			var arr = [];
			var theRequest = new Object();
			if(url.indexOf("?") != -1) {
				var str = url.substr(1);
				arr = str.split("&");
				for(var i = 0; i < arr.length; i++) {
					theRequest[arr[i].split("=")[0]] = unescape(arr[i].split("=")[1]);
				}
				return theRequest;
			}
		},

		/**
		 * 获取form数据
		 */
		getFormDataByName: function(formSelector, ignoreNullStr) {

			if(!$(formSelector).length) {
				return false;
			}

			var formData = {},
				domName, val;
			$('input, select, textarea, label', formSelector).each(function() {

				domName = this.name || this.getAttribute('name');
				val = '';

				if(domName) {
					if(this.nodeName == 'LABEL') {
						val = $.trim($(this).text());
					} else {
						val = $.trim(this.value);
					}
					if(ignoreNullStr && val === '') { //空字符字段不记录
						return true; //continue
					}
					formData[domName] = val;
				}
			});

			return formData;
		},
		/**
		 * 根据url中search参数，设置页面查询条件
		 */
		setQueryBySearch: function(formSelector, searchParams) {

			if(!$(formSelector).length || typeof searchParams != 'object') {
				return false;
			}
			for(var fieldName in searchParams) {
				$('[name=' + fieldName + ']', formSelector).val(searchParams[fieldName]);
			}
		},
		/**
		 * 数组去重
		 * @returns {*[]}
		 */
		unique: function(arr) {
			var ret = [];
			for(var i = 0; i < arr.length; i++) {
				var item = arr[i]
				if(ret.indexOf(item) == -1) {
					ret.push(item)
				}
			}
			return ret;
		},
		/**
		 * 为undefined字段设置默认值
		 */
		defVal: function(val, defaultVal) {

			if(defaultVal == undefined) {
				defaultVal = '';
			}
			return val || defaultVal;
		},

		inArray: function(needle, arrObj) {
			var list = arrObj || [];
			if(Object.prototype.toString.call(list) !== '[object Array]' || !list.length) {
				return false;
			}

			for(var i = 0, len = list.length, item; i < len, item = list[i]; i++) {
				if(needle == item) {
					return true;
				}
			}

			return false;
		},

		//替换回车符
		replaceEnter: function(str) {
			if(str) {
				str = str.replace(/\r\n/g, "<br/>")
				str = str.replace(/\n/g, "<br/>");
			}
			return str;
		},

		/**
		 * 获取当前页码数（目前仅从hash中获取）
		 * varName: 页码变量名
		 */
		getCurrPage: function(varNameInHash) {

			varNameInHash = varNameInHash || 'pageNo';
			var currPage = 1;

			var reg = new RegExp("(^|&)" + varNameInHash + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
			var r = window.location.hash.substr(1).match(reg); //匹配目标参数
			if(r != null) {
				currPage = decodeURI(r[2]);
			}
			return currPage;
		},

		//获取当前域名，末位加"/"
		getCurrDomain: function() {
			return comUrl.charAt(comUrl.length - 1) != "/" ? comUrl + '/' : comUrl;
		},
		
		//传给接口之前的字段处理
        encVal: function (val) {

            if (!val) {
                return '';
            }
            val = $.trim(val);

            if (!val.replace) {
                return val;
            }

            val = val.replace(/%/g, '%25').replace(/\+/g, '%2B');

            return val;
        },

        //字段decode
        decVal: function (val) {

            if (!val) {
                return '';
            }
            val = $.trim(val);

            if (!val.replace) {
                return val;
            }

            val = val.replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
                .replace(/\r\n/g, "<br/>").replace(/\n/g, "<br/>");
            return val;
        },
		/**
		 * 处理表单数据
		 * @param {Object} formName
		 * @param {Object} linearize
		 * @param {Object} isNoSearch
		 */
		dealFormFilter: function(formName, linearize, isNoSearch) { //form中dom保存
			var params = {};
			var searchParams = $("." + formName + " select,." + formName + " input,." + formName + " textarea");
			if(searchParams && searchParams.length) {
				for(var i = 0; i < searchParams.length; i++) {
					var $selector = $(searchParams[i]);

					if(!isNoSearch && $selector.attr('_noSearch')) {
						continue;
					}
					var param = $selector.attr("name");
					
					var value = utilModule.encVal($selector.val()) || '';
					if(typeof value == 'object' && linearize) {
						value = value.join(',');
					}
					var type = $selector.attr("type");
					if(type == 'radio') {
						value = $("input[name='" + param + "']:checked").val();
					}
					if(param != "undefined" && param != undefined && "" != param) {
						value ? params[param] = value : "";
					}
				}
			}
			console.log("params:", params);
			return params;
		},
		
		/**
		 * undefined 校验
		 * @param {Object} inputValue
		 */
		checkUndefined: function(inputValue) {
			if(typeof(inputValue) == 'undefined' || inputValue == undefined) {
				return "";
			} else {
				return inputValue;
			}
		},
		showLoading:function(showDiv){
		   $("."+showDiv).css("display","none");
		},
		closeLoading:function(showDiv){
		   $("."+showDiv).css("display","none");
		}
	}
})();